import { Avatar, Button, Flex, Input, Upload } from "antd"
import { useEffect, useState } from "react"
import { reqDelFile } from "../api/uploadApi"

type Props = {
    label:string
    content: string
    status: boolean // true编辑 false展示
    type?: "text" | "img"
    EditFn?: () => void
    CloseFn?: () => void
    updateFn?: (obj:object) => void
}
export const Edit = ({
    status,
    content,
    type,
    EditFn,
    CloseFn,
    updateFn,
    label,
}: Props) => {
    // 两种形态
    const [value,setValue] = useState("")
    useEffect(()=>{
        if(status){
            setValue("")
        }
    },[status])
    const statusEdit = (
        <Flex gap={20} align="center">
            {type == "img" ? (
                <Upload 
                listType="picture-circle"
                action="/dev-api/api/upload"
                name="file"
                onChange={async (e)=>{
                    if(e.file.status === "done"){
                        setValue(e.file.response.data)
                    }
                    if(e.file.status === "removed"){
                        await reqDelFile(value)
                        setValue("")
                    }
                }}
                >
                    {value === "" && "+"}
                </Upload>
            ) : (
            <Input 
            defaultValue={content} 
            onChange={(e)=>setValue(e.target.value)}
            ></Input>)}
            <Button
                type="primary"
                onClick={()=>updateFn && updateFn({ [label]: value })}
            >确定修改
            </Button>
            <Button onClick={CloseFn}>取消</Button>
        </Flex>
    )
    const statusShow = (
        <Flex gap={20} align="center">
            {type == "img" ? (
                <Avatar size={64} src={content}></Avatar>
            ):(<div>{content}</div>)}
            <Button type="primary" size="small" onClick={EditFn}>修改</Button>
        </Flex>
    )
    return status ? statusEdit : statusShow
}